package com.my.search.service.serviceImpl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.AppHttpCodeEnum;
import com.my.model.search.dtos.UserSearchDto;
import com.my.search.pojos.ApAssociateWords;
import com.my.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取联想词
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getAssociationWord(UserSearchDto dto) {
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //分页查询
        if(dto.getPageSize() > 20) {
            dto.setPageSize(20);
        }

        //模糊查询
        Query query = Query.query(Criteria.where("associateWords").regex(".*\\" + dto.getSearchWords() + ".*"));
        query.limit(dto.getPageSize());
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(apAssociateWords);
    }
}
